package uk.org.scuts.bantstadium2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Vector;

import org.w3c.dom.Document;

import android.os.Bundle;
import android.os.Process;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class ActivityCustomise extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customise_main);
        ResetView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0,  1,  1, "Clear data");
    	menu.add(0, 99, 99, "Exit");
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    	case 1:
    		DeleteCustomData();
    		return true;
    	case 99:
    		Process.killProcess(Process.myPid());
    		return true;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
    public void DeleteCustomData()
    {
    	AlertDialog.Builder confirmBox = new AlertDialog.Builder(this);
    	confirmBox.setIcon(R.drawable.ic_launcher);
    	confirmBox.setMessage("All custom characters will be removed, and others will be returned to default values.");
    	confirmBox.setTitle("Reset custom data?");
    	
    	confirmBox.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			FullDeleteConfirmed();
    		}
    	});
    	
    	confirmBox.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			// Sack all
    		}
    	});
    	
    	confirmBox.show();
    }
    
    public void FullDeleteConfirmed()
    {
    	Utils.DeleteXML(this, Utils.CustomCharsFilename());
		Toast.makeText(this, "All custom data has been reset", Toast.LENGTH_LONG).show();
		_currentName = "";
		ResetView();
    }
    
    public class EditCharListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent,
                                   View view,
                                   int pos,
                                   long id) {
        	_currentName = parent.getItemAtPosition(pos).toString();
        	PopulateFields();
        }

        public void onNothingSelected(AdapterView<?> parent) {
          // Do nothing.
        }
    }
    
    public void ResetView()
    {
    	_doc = Utils.ParseXML(Utils.OpenXML(this, Utils.CustomCharsFilename(), Utils.CharsFilename()));
        
        ArrayList<String> nameList = Utils.GetNameList(_doc);
        nameList.remove("Dean");

        Collections.sort(nameList);       
        ArrayAdapter<String> nameAdapter = 
        	new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, nameList);
        Spinner nameSpin = (Spinner) findViewById(R.id.nameSpinner);
        nameSpin.setAdapter(nameAdapter);
		int pos = nameAdapter.getPosition(_currentName);
		nameSpin.setSelection(pos);
        nameSpin.setOnItemSelectedListener(new EditCharListener());
        
        ArrayList<String> attackList = new AttackManager().GetAttackNames();
        Collections.sort(attackList);       
        ArrayAdapter<String> attackAdapter = 
        	new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, attackList);
        Spinner attack0Spin = (Spinner) findViewById(R.id.attack0Spinner);
        attack0Spin.setAdapter(attackAdapter);
        Spinner attack1Spin = (Spinner) findViewById(R.id.attack1Spinner);
        attack1Spin.setAdapter(attackAdapter);
        Spinner attack2Spin = (Spinner) findViewById(R.id.attack2Spinner);
        attack2Spin.setAdapter(attackAdapter);
        Spinner attack3Spin = (Spinner) findViewById(R.id.attack3Spinner);
        attack3Spin.setAdapter(attackAdapter);
        
        ArrayList<String> genders = new ArrayList<String>();
        genders.add("Male");
        genders.add("Female");
        ArrayAdapter<String> genderAdapter = 
        	new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, genders);
        Spinner genderSpin = (Spinner) findViewById(R.id.genderSpinner);
        genderSpin.setAdapter(genderAdapter);
    }
    
    @SuppressWarnings("unchecked")
	public void PopulateFields()
    {    	
    	CharManager cm = new CharManager(_doc);
    	
    	CharBase base = cm.at(_currentName);
    	
    	// Read from CharBase
    	String gender = "Male";
    	if (base._gender == Character.Gender.FEMALE) {
    		gender = "Female";
    	}
    	String attack = base._attack;
    	String defense = base._defense;
    	String cunning = base._cunning;
    	String speed = base._speed;
    	String hp = base._hp;
    	
    	Vector<String> attacks = new Vector<String>();
    	attacks.add(base._attack0);
    	attacks.add(base._attack1);
    	attacks.add(base._attack2);
    	attacks.add(base._attack3);
    	
    	// Grab views
    	EditText nameBox = (EditText) findViewById(R.id.nameBox);
    	Spinner genderSpin = (Spinner) findViewById(R.id.genderSpinner);
    	EditText attackBox = (EditText) findViewById(R.id.attackBox);
    	EditText defenseBox = (EditText) findViewById(R.id.defenseBox);
    	EditText cunningBox = (EditText) findViewById(R.id.cunningBox);
    	EditText speedBox = (EditText) findViewById(R.id.speedBox);
    	EditText hpBox = (EditText) findViewById(R.id.hpBox);
    	Vector<Spinner> attackSpinners = new Vector<Spinner>();
    	attackSpinners.add((Spinner) findViewById(R.id.attack0Spinner));
    	attackSpinners.add((Spinner) findViewById(R.id.attack1Spinner));
    	attackSpinners.add((Spinner) findViewById(R.id.attack2Spinner));
    	attackSpinners.add((Spinner) findViewById(R.id.attack3Spinner));
    	
    	// Populate name
    	nameBox.setText(_currentName);
    	
    	// Populate gender
    	// Any ideas how to do this without a warning?
		ArrayAdapter<String> genderAdapter = (ArrayAdapter<String>) genderSpin.getAdapter();
    	int genderPos = genderAdapter.getPosition(gender);
    	genderSpin.setSelection(genderPos);
    	
    	// Populate stats
    	attackBox.setText(attack);
    	defenseBox.setText(defense);
    	cunningBox.setText(cunning);
    	speedBox.setText(speed);
    	hpBox.setText(hp);
    	
    	// Populate attacks
    	Iterator<String> attackIte = attacks.iterator();
    	Iterator<Spinner> spinIte = attackSpinners.iterator();
    	while (attackIte.hasNext() && spinIte.hasNext() )
    	{
    		Spinner spin = spinIte.next();
    		// Any ideas how to do this without a warning?
    		ArrayAdapter<String> attacksAdapter = (ArrayAdapter<String>) spin.getAdapter();
    		int pos = attacksAdapter.getPosition(attackIte.next());
    		spin.setSelection(pos);
    	}
    }
    
    public void Submit (View view)
    {
    	// Grab views
    	EditText nameBox = (EditText) findViewById(R.id.nameBox);
    	Spinner genderSpin = (Spinner) findViewById(R.id.genderSpinner);
    	EditText attackBox = (EditText) findViewById(R.id.attackBox);
    	EditText defenseBox = (EditText) findViewById(R.id.defenseBox);
    	EditText cunningBox = (EditText) findViewById(R.id.cunningBox);
    	EditText speedBox = (EditText) findViewById(R.id.speedBox);
    	EditText hpBox = (EditText) findViewById(R.id.hpBox);
    	Vector<Spinner> attackSpinners = new Vector<Spinner>();
    	attackSpinners.add((Spinner) findViewById(R.id.attack0Spinner));
    	attackSpinners.add((Spinner) findViewById(R.id.attack1Spinner));
    	attackSpinners.add((Spinner) findViewById(R.id.attack2Spinner));
    	attackSpinners.add((Spinner) findViewById(R.id.attack3Spinner));
    	
    	String newName = nameBox.getText().toString();
    	String attackString = attackBox.getText().toString();
    	String defenseString = defenseBox.getText().toString();
    	String cunningString = cunningBox.getText().toString();
    	String hpString = hpBox.getText().toString();
    	String speedString = speedBox.getText().toString();
    	
    	if (newName.isEmpty() ||
    	    attackString.isEmpty() ||
    	    defenseString.isEmpty() ||
    	    cunningString.isEmpty() ||
    	    hpString.isEmpty() ||
    	    speedString.isEmpty())
    	{
    		Toast.makeText(this, "All fields must be populated", Toast.LENGTH_SHORT).show();
    		return;
    	}
    	else if (!newName.equals(_currentName) && Utils.GetNameList(_doc).contains(newName))
    	{
    		Toast.makeText(this, newName + " already exists, cannot rename " + _currentName + " to " + newName, Toast.LENGTH_SHORT).show();
    		return;
    	}
    	
    	// Build CharBase
    	CharBase base = new CharBase(genderSpin.getSelectedItem().toString(),
    			                     attackString,
    			                     defenseString,
    			                     cunningString,
    			                     hpString,
    			                     speedString,
    			                     attackSpinners.elementAt(0).getSelectedItem().toString(),
    			                     attackSpinners.elementAt(1).getSelectedItem().toString(),
    			                     attackSpinners.elementAt(2).getSelectedItem().toString(),
    			                     attackSpinners.elementAt(3).getSelectedItem().toString());
    	
    	CharManager cm = new CharManager(_doc);
    	cm.Replace(_currentName, newName, base);
    	Utils.SaveXML(this, cm.ToXML(), Utils.CustomCharsFilename());
    	
    	_currentName = newName;
    	Toast.makeText(this, newName + " saved", Toast.LENGTH_SHORT).show();
    	
    	ResetView();
    }
    
    public void AddCharacter (View view)
    {
    	String newName = "New";
    	
    	// Build CharBase
    	CharBase base = new CharBase("Male",
    			                     "5",
    			                     "5",
    			                     "5",
    			                     "50",
    			                     "5",
    			                     "Punch",
    			                     "Kick",
    			                     "Flip Off",
    			                     "Jab");
    	
    	CharManager cm = new CharManager(_doc);
    	cm.Add(newName, base);
    	Utils.SaveXML(this, cm.ToXML(), Utils.CustomCharsFilename());
    	
    	_currentName = newName;
    	ResetView();
    }
    
    public void DeleteConfirmed()
    {
    	CharManager cm = new CharManager(_doc);
    	cm.Delete(_currentName);
    	Utils.SaveXML(this, cm.ToXML(), Utils.CustomCharsFilename());
    	ResetView();
    }
    
    public void DeleteCharacter (View view)
    {
    	AlertDialog.Builder confirmBox = new AlertDialog.Builder(this);
    	confirmBox.setIcon(R.drawable.ic_launcher);
    	confirmBox.setMessage("Delete " + _currentName + "?");
    	
    	confirmBox.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			DeleteConfirmed();
    		}
    	});
    	
    	confirmBox.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			// Sack all
    		}
    	});
    	
    	confirmBox.show();
    }
    
    public void Back (View view)
    {
    	finish();
    }
    
    // Members
    Document _doc;
    String _currentName;
}
